/**   
* @Title: ConnectionPool.java 
* @Package com.element5th.comm 
* @Description: 
* @author 第五小组  
* @date 2012-11-4 上午10:59:45 
* @version V1.0   
*/ 
package com.element5th.comm;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.Properties;

import com.element5th.shop.comm.SystemException;

/** 
 * @ClassName: ConnectionPool 
 * @Description: 
 * @author  第五小组
 * @date 2012-11-4 上午10:59:45 
 *  
 */
public final class ConnectionPool {
	private static String url;
	private static String className;
	private static Connection conn = null;
	
	
	private static int initSize = 5;
	private static int maxsize = 10;
	private static int number = 0;
	private static LinkedList<Connection> list = new LinkedList<Connection>();
	
	private ConnectionPool(){
	}
	
	static {
		try {
			Properties ps = new Properties();
			InputStream inStream = ConnectionPool.class.getClassLoader()
					.getResourceAsStream("com/element5th/comm/jdbc.properties");
			ps.load(inStream);
			className = ps.getProperty("className");
			url = ps.getProperty("url");
			Class.forName(className);
			for(int i=0; i < initSize; i++){
				conn = DriverManager.getConnection(url);
				conn.setAutoCommit(false);
				number++;
				list.addFirst(conn);
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static Connection getConnection() {
		if(list.isEmpty() != true) {
			conn = list.removeLast();
			return conn;
		} else {
			if (number < maxsize) {
				try {
					conn = DriverManager.getConnection(url);
					conn.setAutoCommit(false);
					number++;
					return conn;
				} catch (SQLException e) {
					throw new SystemException(2007,"获取数据库连接失败");
				}
			} else {
				throw new SystemException(2006,"用户连接数过多，请稍后再试");
			}
		}
	}
	
	
	public static void returnConnection(Connection conn) {
		if (list.size() >initSize) {
			try {
				conn.close();
				number++;
			} catch (SQLException e) {
				e.printStackTrace();
			}
		} else {
			list.addFirst(conn);
		}
	}
	
	
}
